package com.vanke.devops.api.controller.users;

import com.vanke.core.bean.ApiBaseResponse;
import com.vanke.core.bean.PagingResponse;
import com.vanke.core.util.CodecUtil;
import com.vanke.core.util.StringUtil;
import com.vanke.core.web.WebContext;
import com.vanke.devops.api.base.AbstractController;
import com.vanke.devops.api.controller.users.form.UsersForm;
import com.vanke.devops.dal.model.Users;
import com.vanke.devops.domain.domain.users.IUsersService;
import com.vanke.devops.domain.domain.users.dto.UsersDTO;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 用户表  前端控制器
 * </p>
 *
 * @author 陈景阳
 * @since 2018-03-11
 */
@RestController
@RequestMapping("/users")
public class UsersController extends AbstractController<IUsersService> {

    @GetMapping(value = "/page/{pageSize}/{pageNo}")
    public PagingResponse list(@ModelAttribute UsersForm form, @PathVariable("pageSize") Integer pageSize, @PathVariable("pageNo") Integer pageNo)  {
        return super.queryWithPage(this.convert(form), pageSize, pageNo);
    }

    @GetMapping(value = "/{id}")
    public ApiBaseResponse get(@PathVariable("id") Integer id)  {
        return super.getDetail(id);
    }

    @PutMapping(value = "/{id}")
    public ApiBaseResponse update(@RequestBody UsersForm form, @PathVariable("id") Integer id)  {
        Users param = this.convert(form);
        param.setId(id);
        return super.updateRecord(param);
    }

    @DeleteMapping(value = "/{id}")
    public ApiBaseResponse delete(@PathVariable("id") Integer id)  {
        return super.deleteRecord(id);
    }

    @PostMapping
    public ApiBaseResponse add(@RequestBody UsersForm form)  {
        return super.addRecord(this.convert(form));
    }

    @GetMapping("/current")
    public ApiBaseResponse current(){
        UsersDTO usersDTO = service.getById(service.getCurrUser());
        return setResponse(usersDTO);
    }

    private Users convert(UsersForm form){
        Users users = new Users();
        users.setLoginId(form.getLoginId());
        users.setUsername(form.getUsername());
        if(StringUtil.isNotEmpty(form.getPassword())){
            users.setPassword(CodecUtil.encryptMD5(form.getPassword()));
        }
        return users;
    }
}